package com.xunwulian.cmpp.pdu;

import com.xunwulian.cmpp.sms.PDU;
import org.codehaus.jackson.annotate.JsonIgnore;

public abstract class CmppPDU extends PDU {

//    public int sequenceNumber = 0;

    public boolean sequenceNumberChanged = false;

    public CmppPDUHeader header = new CmppPDUHeader();

    public CmppPDU(int commandId) {
        header.setCommandId(commandId);
    }

    public int getSequenceNumber() {
        return header.getSequenceNumber();
    }

    public void setCommandLength(int cmdLen) {
        header.setCommandLength(cmdLen);
    }

    public void setCommandId(int cmdId) {
        header.setCommandId(cmdId);
    }

    public void setSequenceNumber(int seqNr) {
        header.setSequenceNumber(seqNr);
    }

//    public void assignSequenceNumber() {
//        assignSequenceNumber(false);
//    }

//    public void assignSequenceNumber(boolean always) {
//        if ((!sequenceNumberChanged) || always) {
//            synchronized (this) {
//                setSequenceNumber(++sequenceNumber);
//            }
//            sequenceNumberChanged = true;
//        }
//    }


    public boolean equals(Object object) {
        if ((object != null) && (object instanceof CmppPDU)) {
            CmppPDU pdu = (CmppPDU) object;
            return pdu.getSequenceNumber() == getSequenceNumber();
        } else {
            return false;
        }
    }

    @JsonIgnore
    public String getSequenceNumberAsString() {
        int data = header.getSequenceNumber();
        byte[] intBuf = new byte[4];
        intBuf[3] = (byte) (data & 0xff);
        intBuf[2] = (byte) ((data >>> 8) & 0xff);
        intBuf[1] = (byte) ((data >>> 16) & 0xff);
        intBuf[0] = (byte) ((data >>> 24) & 0xff);
        return new String(intBuf);
    }

    public boolean isSequenceNumberChanged() {
        return sequenceNumberChanged;
    }

    public void setSequenceNumberChanged(boolean sequenceNumberChanged) {
        this.sequenceNumberChanged = sequenceNumberChanged;
    }

    public abstract boolean isRequest();

    public abstract boolean isResponse();

}
